//
//  APIManager.m
//  ReactiveCocoaUserDemo
//
//  Created by zsp on 2017/3/14.
//  Copyright © 2017年 zsp. All rights reserved.
//

#import "APIManager.h"
#import <AFNetworking.h>
#import <ReactiveCocoa.h>
#import <RACAFNetworking.h>

#import "XYUser.h"

@interface APIManager ()
@property(nonatomic, strong)AFHTTPSessionManager *httpSessionManager;
@end

@implementation APIManager

+(instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static APIManager *manager;
    dispatch_once(&onceToken, ^{
        manager=[[self alloc]init];
    });
    return manager;
}

- (instancetype)init {
    if (self=[super init]) {
        self.httpSessionManager=[AFHTTPSessionManager manager];
    }
    return self;
}

//第三版：加入 AFNetworking-RACExtensions
- (RACSignal*)getUserByExtEmail:(NSString *)email {
    NSString *path = @"https://your.server.address/api/user";
    NSDictionary *params = @{ @"email":email };
    return [[self.httpSessionManager rac_GET:path parameters:params ] flattenMap:^RACStream *(RACTuple *tuple) {
        NSError *error=nil;
        XYUser *user = [MTLJSONAdapter modelOfClass:[XYUser class] fromJSONDictionary:tuple.first error:&error];
        return error?[RACSignal error:error]:[RACSignal return:user];
    } ];
}


//第二版：用 RACSignal 包起來
- (RACSignal*)getUserByEmail:(NSString *)email {
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        NSString *path = @"https://your.server.address/api/user";
        NSDictionary *params = @{ @"email":email };
        
        NSURLSessionDataTask *task=[self GET:path parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
            NSError *error = nil;
            XYUser *user = [MTLJSONAdapter modelOfClass:[XYUser class] fromJSONDictionary:responseObject error:&error];
            if (error) {
                [subscriber sendError:error];
            } else {
                [subscriber sendNext:user];
                [subscriber sendCompleted];
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [subscriber sendError:error];
        }];
        
        [task resume];
        
        return [RACDisposable disposableWithBlock:^{
            [task cancel];
        }];
    }];
}

//第一版：單純使用 AFNetworking
- (NSURLSessionDataTask *)getUserByEmail:(NSString *)email success:(void (^)(XYUser *user))success failure:(void (^)(NSError *error))failure {
    NSString *path = @"https://your.server.address/api/user";
    NSDictionary *params = @{ @"email":email };
    return [self GET:path parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success) {
            NSError *error = nil;
            XYUser *user = [MTLJSONAdapter modelOfClass:[XYUser class] fromJSONDictionary:responseObject error:&error];
            if (error) {
                if (failure) {
                    failure(error);
                }
            } else {
                success(user);
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

- (NSURLSessionDataTask *)GET:(NSString *)URLString
                   parameters:(id)parameters
                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                      failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    return [self.httpSessionManager GET:URLString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        success(task, responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(task, error);
    }];
}

@end
